import store from "@/store/index";
import guardStore from "@/apps/admin/store/guard";

/**
 * 权限验证
 * @param permission
 * @param mode
 */
export function auth(permission: string | string[], mode: 'OR' | 'AND' = 'OR') {
    const guard = guardStore(store)
    if (typeof permission === 'string') {
        permission = [permission];
    }
    if (guard.id) {
        if (mode === 'OR') {
            for (let item of permission) {
                if (guard.power.indexOf(item) > -1) return true
            }
            return false
        } else {
            for (let item of permission) {
                if (guard.power.indexOf(item) === -1) return false
            }
            return true
        }
    }
    return false
}


/**
 * 权限指令
 * @type {{name: string, directive: {mounted(*, *): (boolean|*)}}}
 */
export const directive: { name: string, directive: any } = {
    name: 'auth',
    directive: {
        mounted(el: any, bindings: any) {
            let value = bindings.value;
            let mode = bindings.modifiers.and === true ? 'AND' : 'OR'
            let permission = []
            if (typeof value === 'string') {
                permission.push(value)
            } else if (value instanceof Array) {
                permission = value
            }
            if (permission.length === 0) return true
            if (!auth(permission, mode === 'AND' ? 'AND' : 'OR')) {
                return el.parentNode.removeChild(el);
            }
            return true
        }
    }
}